<template>
	<div>
		<el-card class="phone-cont">
			<div slot="header">
				<span>修改密码</span>
			</div>

			<div class="addphone">
				<el-form
					:model="FormData"
					:rules="rules"
					label-width="100px"
					ref="FormData"
					status-icon
				>
					<el-form-item label="原密码" prop="oldPwd">
						<el-input v-model="FormData.oldPwd"></el-input>
					</el-form-item>
					<el-form-item label="新密码" prop="newPwd">
						<el-input v-model="FormData.newPwd"></el-input>
					</el-form-item>
					<el-form-item label="确认新密码" prop="confirmPwd">
						<el-input v-model="FormData.confirmPwd"></el-input>
					</el-form-item>
					<el-form-item>
						<el-button class="fff gree" @click="handleComfirm">确定</el-button>
						<el-button @click="handleReset">重置</el-button>
					</el-form-item>
				</el-form>
			</div>
		</el-card>
	</div>
</template>

<script>
	import { api_users_checkoldpwd,api_users_editpwd } from "@/apis/user";

	export default {
		data() {
			const checkNewPwd = (rule, value, callback) => {
				if (!value) {
					callback(new Error("请输入新密码"));
				} else if (!/^.{3,20}$/.test(value)) {
					callback(new Error("长度为3-20的所有字符"));
				} else {
					// 验证是否与确认新密码一致
					// 确认新密码不为空才做一致性判断
					if (this.FormData.confirmPwd) {
						this.$refs.FormData.validateField("checkConfirmPwd");
					}
					// 验证通过
					callback();
				}
			};
			const checkConfirmPwd = (rule, value, callback) => {
				if (!value) {
					callback(new Error("请确认新密码"));
				} else if (!/^.{3,20}$/.test(value)) {
					callback(new Error("长度为3-20的所有字符"));
				} else {
					// 判断是否与新密码一致
					if (
						value !== this.FormData.newPwd &&
						this.FormData.newPwd
					) {
						callback(new Error("与新密码不一致，请重新输入"));
					}
					callback();
				}
			};
			// 自定义验证原密码
			const checkOldPwd = async (rule, value, callback) => {
				if (!value) {
					callback(new Error("请输入原密码"));
				} else {
					// 发送请求确定是否与原密码一致
					const res = await api_users_checkoldpwd({ oldPwd: value });
					if (res.data.code === 201) {
						callback(new Error(res.data.msg));
					}
					callback();
				}
			};
			return {
				FormData: {
					oldPwd: "",
					newPwd: "",
					confirmPwd: "",
				},
        rules:{
          oldPwd: { validator: checkOldPwd, trigger: "blur" },
          newPwd: { validator: checkNewPwd, trigger: "blur" },
          confirmPwd: { validator: checkConfirmPwd, trigger: "blur" },
        }
			};
		},
    methods:{
      async handleComfirm(){
        const res = await api_users_editpwd({
          newPwd:this.FormData.newPwd
        })
        if(res.data.code==0){
           localStorage.clear()
           this.$router.push('/login')
        }
        // console.log(res);
      },
      // 重置
handleReset(){
  this.$refs.FormData.resetFields();
}
    },
    

	};
</script>

<style lang="scss" scoped>
	.el-input {
		width: 300px;
		::v-deep .el-input__inner {
			width: 300px;
		}
	}
</style>
